package com.damai.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import com.citywithincity.db.Db;
import com.citywithincity.db.meta.ColumnStruct;
import com.citywithincity.db.meta.DbStructFactory;
import com.citywithincity.db.meta.TableStruct;
import com.damai.utils.SyncModel;

public class StructsModel {

	
	public Map<String, List<ColumnStruct>> exportDiff() throws IOException{
		SyncModel syncModel = new SyncModel();
		syncModel.table("all_tab_columns");
		syncModel.select("TABLE_NAME,COLUMN_NAME");
		syncModel.condition("OWNER", "ECARD2013");
		List<Map<String, Object>> current = syncModel.getList(0,100000);
		
		Map<String, Boolean> usingMap = new HashMap<String, Boolean>();
		for (Map<String, Object> record : current) {
			usingMap.put((String)record.get("TABLE_NAME").toString().toUpperCase()+record.get("COLUMN_NAME").toString().toUpperCase(), true);
		}
		
		Map<String, ColumnStruct> currentMap = new HashMap<String, ColumnStruct>();
		Collection<TableStruct> tableStructs = Db.getStruct(0).getTableStructs(DbStructFactory.STRUCT_USING);
		
		for (TableStruct tableStruct : tableStructs) {
			Collection<ColumnStruct> columnStructs = tableStruct.getColumns();
			for (ColumnStruct columnStruct : columnStructs) {
				currentMap.put(tableStruct.getName().toUpperCase()+columnStruct.getName().toUpperCase(),columnStruct);
			}
		}
		
		
		Set<String> currentSet = new HashSet<String>();
		currentSet.addAll(currentMap.keySet());
		Set<String> usingSet = usingMap.keySet();
		currentSet.removeAll(usingSet);
		
		
		List<ColumnStruct> diff = new ArrayList<ColumnStruct>();
		for (String key : currentSet) {
			diff.add(currentMap.get(key));
		}
		
		Map<String, List<ColumnStruct>> map =  new TreeMap<String, List<ColumnStruct>>();
		for (ColumnStruct struct : diff) {
			
			List<ColumnStruct> list = map.get(struct.getTable());
			if(list==null){
				list = new ArrayList<ColumnStruct>();
				map.put(struct.getTable(), list);
			}
			list.add(struct);
			
		}
		
		for (Entry<String, List<ColumnStruct>> entry : map.entrySet()) {

			
		}
		return map;
	}
}
